<template>
  <div class="price-analysis">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>价格分析</h1>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <!-- 价格区间筛选 -->
        <el-card class="filter-card">
          <el-form :inline="true" :model="filterForm">
            <el-form-item label="价格区间">
              <el-input-number
                v-model="filterForm.minPrice"
                :min="0"
                placeholder="最低价格"
                style="width: 120px;"
              />
              <span style="margin: 0 10px;">-</span>
              <el-input-number
                v-model="filterForm.maxPrice"
                :min="0"
                placeholder="最高价格"
                style="width: 120px;"
              />
            </el-form-item>
            <el-form-item label="分类">
              <el-select v-model="filterForm.category" placeholder="选择分类" clearable>
                <el-option
                  v-for="item in categories"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="applyFilter">应用筛选</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 价格统计概览 -->
        <el-row :gutter="20" class="overview-cards">
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="card-content">
                <div class="card-icon">
                  <el-icon size="40" color="#409EFF"><TrendCharts /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-title">平均价格</div>
                  <div class="card-value">¥{{ priceStats.avgPrice }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="card-content">
                <div class="card-icon">
                  <el-icon size="40" color="#67C23A"><ArrowDown /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-title">最低价格</div>
                  <div class="card-value">¥{{ priceStats.minPrice }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="card-content">
                <div class="card-icon">
                  <el-icon size="40" color="#E6A23C"><ArrowUp /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-title">最高价格</div>
                  <div class="card-value">¥{{ priceStats.maxPrice }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="overview-card">
              <div class="card-content">
                <div class="card-icon">
                  <el-icon size="40" color="#F56C6C"><DataAnalysis /></el-icon>
                </div>
                <div class="card-info">
                  <div class="card-title">价格标准差</div>
                  <div class="card-value">¥{{ priceStats.stdPrice }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 价格分析图表 -->
        <el-row :gutter="20" class="charts-section">
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>价格分布直方图</span>
              </template>
              <div class="chart-container">
                <v-chart :option="priceHistogramOption" style="height: 400px;" />
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="12">
            <el-card>
              <template #header>
                <span>价格区间分布</span>
              </template>
              <div class="chart-container">
                <v-chart :option="priceRangeOption" style="height: 400px;" />
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 价格趋势分析 -->
        <el-row :gutter="20" class="trend-section">
          <el-col :span="24">
            <el-card>
              <template #header>
                <span>价格趋势分析</span>
              </template>
              <div class="chart-container">
                <v-chart :option="priceTrendOption" style="height: 400px;" />
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 价格异常检测 -->
        <el-card class="anomaly-card">
          <template #header>
            <span>价格异常检测</span>
          </template>
          <el-table :data="priceAnomalies" style="width: 100%">
            <el-table-column prop="title" label="商品名称" />
            <el-table-column prop="price" label="价格">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" />
            <el-table-column prop="anomalyType" label="异常类型">
              <template #default="scope">
                <el-tag :type="scope.row.anomalyType === 'high' ? 'danger' : 'warning'">
                  {{ scope.row.anomalyType === 'high' ? '价格过高' : '价格过低' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="deviation" label="偏离度">
              <template #default="scope">
                {{ scope.row.deviation }}%
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import axios from 'axios'

use([CanvasRenderer, BarChart, LineChart, PieChart, GridComponent, TooltipComponent, LegendComponent])

export default {
  name: 'PriceAnalysis',
  components: {
    VChart
  },
  setup() {
    const filterForm = ref({
      minPrice: null,
      maxPrice: null,
      category: ''
    })

    const categories = ref([])
    const priceStats = ref({
      avgPrice: 0,
      minPrice: 0,
      maxPrice: 0,
      stdPrice: 0
    })
    const priceAnomalies = ref([])

    const priceHistogramOption = ref({
      title: {
        text: '价格分布直方图',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value',
        name: '商品数量'
      },
      series: [
        {
          name: '商品数量',
          type: 'bar',
          data: []
        }
      ]
    })

    const priceRangeOption = ref({
      title: {
        text: '价格区间分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '价格区间',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 0, name: '0-50元' },
            { value: 0, name: '50-100元' },
            { value: 0, name: '100-200元' },
            { value: 0, name: '200元以上' }
          ]
        }
      ]
    })

    const priceTrendOption = ref({
      title: {
        text: '价格趋势分析',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value',
        name: '价格 (元)'
      },
      series: [
        {
          name: '平均价格',
          type: 'line',
          data: []
        }
      ]
    })

    const fetchCategories = async () => {
      try {
        const response = await axios.get('/api/category/list')
        categories.value = response.data
      } catch (error) {
        console.error('获取分类列表失败:', error)
      }
    }

    const fetchPriceAnalysis = async () => {
      try {
        const response = await axios.get('/api/price/analysis', {
          params: filterForm.value
        })
        
        priceStats.value = response.data.stats
        priceAnomalies.value = response.data.anomalies
        
        // 更新图表数据
        priceHistogramOption.value.xAxis.data = response.data.histogram.bins
        priceHistogramOption.value.series[0].data = response.data.histogram.counts
        
        priceRangeOption.value.series[0].data = response.data.rangeDistribution
        
        priceTrendOption.value.xAxis.data = response.data.trend.dates
        priceTrendOption.value.series[0].data = response.data.trend.prices
      } catch (error) {
        console.error('获取价格分析数据失败:', error)
      }
    }

    const refreshData = () => {
      fetchCategories()
      fetchPriceAnalysis()
    }

    const applyFilter = () => {
      fetchPriceAnalysis()
    }

    const resetFilter = () => {
      filterForm.value = {
        minPrice: null,
        maxPrice: null,
        category: ''
      }
      fetchPriceAnalysis()
    }

    onMounted(() => {
      refreshData()
    })

    return {
      filterForm,
      categories,
      priceStats,
      priceAnomalies,
      priceHistogramOption,
      priceRangeOption,
      priceTrendOption,
      refreshData,
      applyFilter,
      resetFilter
    }
  }
}
</script>

<style scoped>
.price-analysis {
  height: 100vh;
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-content h1 {
  margin: 0;
  color: #303133;
}

.el-main {
  padding: 20px;
  background-color: #f5f5f5;
}

.filter-card {
  margin-bottom: 20px;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  margin-right: 20px;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.charts-section {
  margin-bottom: 20px;
}

.trend-section {
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
}

.anomaly-card {
  margin-bottom: 20px;
}
</style> 